// 加载所需的模块
const db = require('../db');
let { md5 } = require('utility');
let jwt = require('jsonwebtoken');

// 1. 加载express
const express = require('express');
// 2. 创建路由对象，实则是个函数类型
const router = express.Router();
//验证账号-中间件
router.use((req, res, next) => {
    let { username, password } = req.body;
    if (/\S{6,12}/.test(password)) {
        next();
    } else {
        next('密码长度必须是6~12位且不能有空格');
    }
});
// 3. 写接口，把接口挂载到 router 上
//注册接口
router.post('/reguser', (req, res) => {
    let { username, password } = req.body;
    password = md5(password);
    db(`select * from user where username="${username}"`, (e, r) => {
        if (e) throw e;
        if (r.length > 0) {
            r.send({
                status: 1,
                message: '用户名被占用了'
            })
        } else {
            let sql = `insert into user set username="${username}",password="${password}"`
            db(sql, (err, result) => {
                if (err) throw err;
                res.send({
                    status: 0,
                    msg: '注册成功'
                });
            })
        }
    });
});
//登录接口
router.post('/login', (req, res) => {
    let username = req.body.username;
    let password = md5(req.body.password);
    db(`select * from user where username='${username}' and password='${password}'`, (err, result) => {
        if (err) throw err;
        if (result.length > 0) {
            let token = jwt.sign({ id: result[0].id }, 'sdf23sd', { expiresIn: '2h' });
            res.send({ status: 0, message: '登录成功', token: 'Bearer ' + token })
        } else {
            res.send({
                status: 1,
                message: '登陆失败'
            })
        }
    })
});
// 错误处理中间件
router.use((err, req, res, next) => {
    // err 就是前面next过来的参数值
    res.send({ status: 1, message: err })
});
// 4.一定要导出 router
module.exports = router;